package com.jiefeng.manager.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jiefeng.manager.common.exception.ExcelImportExportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.*;

/**
 * Excel批量导出工具类
 *
 * Created by WuZhiqi on 2016/5/26.
 */
public class ExcelBatchExport {

    private static Logger logger = LoggerFactory.getLogger(ExcelBatchExport.class);

    public static <T> void xslExcelBatchExport(OutputStream outputStream, Class<T> clazz, List<T> exportMetadataList) throws ExcelImportExportException {
        //工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //第一页
        HSSFSheet sheet = workbook.createSheet();
        //创建标题
        HSSFRow tittleRow = sheet.createRow(0);
        Field[] fields = clazz.getDeclaredFields();
        List<Field> columnFieldList = new ArrayList<Field>();
        for (int i = 0; i < fields.length; i++) {
            ExcelTemplate excelTemplateAnnotation =  fields[i].getAnnotation(ExcelTemplate.class);
            if(null != excelTemplateAnnotation){
                columnFieldList.add(fields[i]);
            }
        }
        Collections.sort(columnFieldList, new Comparator<Field>() {
            @Override
            public int compare(Field field1, Field field2) {
                ExcelTemplate excelTemplateAnnotation1 =  field1.getAnnotation(ExcelTemplate.class);
                ExcelTemplate excelTemplateAnnotation2 =  field2.getAnnotation(ExcelTemplate.class);
                return excelTemplateAnnotation1.columnOrder() - excelTemplateAnnotation2.columnOrder();
            }
        });
        for (int i = 0; i < columnFieldList.size(); i++) {
            ExcelTemplate excelTemplateAnnotation =  columnFieldList.get(i).getAnnotation(ExcelTemplate.class);
            HSSFCell titleCell = tittleRow.createCell(i, HSSFCell.CELL_TYPE_STRING);
            titleCell.setCellValue(excelTemplateAnnotation.columnName());
        }

        //插入数据
        if(null != exportMetadataList){
            for (int i = 0; i < exportMetadataList.size(); i++) {
                HSSFRow dataRow = sheet.createRow(i + 1);
                JSONObject jsonObject = (JSONObject) JSON.toJSON(exportMetadataList.get(i));
                for(int j = 0; j < columnFieldList.size(); j++){
                    HSSFCell cell = dataRow.createCell(j, HSSFCell.CELL_TYPE_STRING);
                    if(jsonObject.get(columnFieldList.get(j).getName()) != null && (jsonObject.get(columnFieldList.get(j).getName()) instanceof Date)){
                        cell.setCellValue(jsonObject.getDate(columnFieldList.get(j).getName()));
                    }else if(jsonObject.get(columnFieldList.get(j).getName()) != null && (jsonObject.get(columnFieldList.get(j).getName()) instanceof Timestamp)){
                        cell.setCellValue(jsonObject.getTimestamp(columnFieldList.get(j).getName()));
                    }else{
                        cell.setCellValue(jsonObject.getString(columnFieldList.get(j).getName()));
                    }
                }
            }
        }

        //输出EXCEL
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            logger.error("|excelBatchExport|IO读写错误|" + e.toString());
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                logger.error("输出EXCEL出错", e);
            }
        }
    }

    public static <T> void xslxExcelBatchExport(OutputStream outputStream, Class<T> clazz, List<T> exportMetadataList) throws ExcelImportExportException{

        //工作薄对象
        XSSFWorkbook workbook = new XSSFWorkbook();
        //第一页
        XSSFSheet sheet = workbook.createSheet();
        //创建标题
        XSSFRow tittleRow = sheet.createRow(0);
        Field[] fields = clazz.getDeclaredFields();
        List<Field> columnFieldList = new ArrayList<Field>();
        for (int i = 0; i < fields.length; i++) {
            ExcelTemplate excelTemplateAnnotation =  fields[i].getAnnotation(ExcelTemplate.class);
            if(null != excelTemplateAnnotation){
                columnFieldList.add(fields[i]);
            }
        }
        Collections.sort(columnFieldList, new Comparator<Field>() {
            @Override
            public int compare(Field field1, Field field2) {
                ExcelTemplate excelTemplateAnnotation1 =  field1.getAnnotation(ExcelTemplate.class);
                ExcelTemplate excelTemplateAnnotation2 =  field2.getAnnotation(ExcelTemplate.class);
                return excelTemplateAnnotation1.columnOrder() - excelTemplateAnnotation2.columnOrder();
            }
        });
        for (int i = 0; i < columnFieldList.size(); i++) {
            ExcelTemplate excelTemplateAnnotation =  columnFieldList.get(i).getAnnotation(ExcelTemplate.class);
            XSSFCell titleCell = tittleRow.createCell(i, HSSFCell.CELL_TYPE_STRING);
            titleCell.setCellValue(excelTemplateAnnotation.columnName());
        }

        //插入数据
        if(null != exportMetadataList){
            for (int i = 0; i < exportMetadataList.size(); i++) {
                XSSFRow dataRow = sheet.createRow(i + 1);
                JSONObject jsonObject = (JSONObject) JSON.toJSON(exportMetadataList.get(i));
                for(int j = 0; j < columnFieldList.size(); j++){
                    XSSFCell cell = dataRow.createCell(j, HSSFCell.CELL_TYPE_STRING);
                    if(jsonObject.get(columnFieldList.get(j).getName()) != null && (jsonObject.get(columnFieldList.get(j).getName()) instanceof Date)){
                        cell.setCellValue(jsonObject.getDate(columnFieldList.get(j).getName()));
                    }else if(jsonObject.get(columnFieldList.get(j).getName()) != null && (jsonObject.get(columnFieldList.get(j).getName()) instanceof Timestamp)){
                        cell.setCellValue(jsonObject.getTimestamp(columnFieldList.get(j).getName()));
                    }else{
                        cell.setCellValue(jsonObject.getString(columnFieldList.get(j).getName()));
                    }
                }
            }
        }
        //输出EXCEL
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            logger.error("|excelBatchExport|IO读写错误|" + e.toString());
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                logger.error("输出EXCEL出错", e);
            }
        }
    }

}
